﻿using Ledict.ConditionExtract.Authority;
using Ledict.ConditionExtract.Base;
using Ledict.ConditionExtract.BLL;
using Ledict.ConditionExtract.Common;
using Ledict.ConditionExtract.Model;
using Ledict.Utility.Common;
using Ledict.Utility.Extension;
using Ledict.Utility.Helper;
using Ledict.Utility.Msg;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Ledict.ConditionExtract.Frm
{
    /// <summary>
    /// 登录窗体
    /// </summary>
    public partial class FrmLogin : BaseForm
    {

        #region 常用变量
        //保存用户名文件路径字符串
        private string path = System.Configuration.ConfigurationManager.AppSettings["ConfigPath"];
        private string DLpath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "DLConfig.txt";
        //保存用户名集合
        ArrayList alUsers = new ArrayList();
        ArrayList alDLInfo = new ArrayList();
        public static string userName = "";
        public static string userDeptId = "";
        private Dictionary<string, DlInfo> dicDLInfo = new Dictionary<string, DlInfo>();
        public static ConfigInfo configInfo=new ConfigInfo();
        #endregion


        #region 
        /// <summary>
        /// 构造函数
        /// </summary>
        public FrmLogin()
        {
            #region 测试表述与正则的匹配无用
            //string str = "本院认为：本案双方当事人争议的焦点为：一、婚生女秦某乙由陈某抚养还是由秦某甲抚养较为合适；二、秦某甲购买挖掘机是否存在62万元债务，应否在本案中一并处理。对于第一个争议焦点，因秦某甲经常在外玩耍，回家较迟，且秦某甲认可其与陈某分居后，婚生女秦某乙大部分时间随陈某生活，原审法院考虑秦某乙年纪尚幼，需要母亲悉心呵护，陈某对秦某乙现有的生活习性较为熟悉，判决秦某乙由陈某抚养，并无不当。对于第二个争议焦点，因陈某对秦某甲提交的用以证明购买挖掘机所形成62万元债务的证据不予质证，故本院对该证据不予认证，秦某甲对此可另行提起诉讼。综上，秦某甲的上诉理由均不能成立，对其上诉请求不予支持。原审判决认定事实清楚，适用法律正确，应予以维持。据此，依照《中华人民共和国民事诉讼法》第一百七十条第一款第（一）项第一百七十五条之规定，判决如下：";

            //System.Text.RegularExpressions.Match ss = System.Text.RegularExpressions.Regex.Match(str, "(?:争议焦点).*(?=$)");
            //str = ss.ToString(); 
            #endregion

            InitializeComponent();
        }
        #endregion

        #region 
        /// <summary>
        /// 加载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmLogin_Load(object sender, EventArgs e)
        {
            string path = "C:\\表述工具数据库比对配置文件.ldt";
            if (File.Exists(path))
            {
                File.Delete(path);
            }
                GetUserInfo(); 
            GetDLInfo();
            cobUserName.DataSource = alUsers;
            cmbDL.DataSource = alDLInfo;
        }
        #endregion

        #region 取消按钮事件
        /// <summary>
        /// 取消按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void colBtnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }
        #endregion

        #region 登录按钮事件
        /// <summary>
        /// 登录按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void colBtnLogin_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(cobUserName.Text.Trim()))
            {
                MsgBox.Warn("请输入用户名！");
                cobUserName.Focus();
                return;
            }
            if (string.IsNullOrEmpty(colTxtPassWord.Text.Trim()))
            {
                MsgBox.Warn("请输入密码！");
                colTxtPassWord.Focus();
                return;
            }
            if (string.IsNullOrEmpty(cmbDL.Text.Trim()))
            {
                MsgBox.Warn("请选择服务器！");
                cmbDL.Focus();
                return;
            }
            AuthorityClient ac = new AuthorityClient();
            loginRes res = ac.Login(cobUserName.Text.Trim(), colTxtPassWord.Text.Trim(), ref Gvar.uo);
            switch (res)
            {
                case loginRes.success:
                    DialogResult = DialogResult.OK;
                    SaveUserInfo(cobUserName.Text.Trim());
                    userName = cobUserName.Text.Trim() + Gvar.uo.m_displayName;
                    userDeptId = Gvar.uo.m_deptId;
                    PublicMethod.UserName = userName;

                    #region MyRegion
                    //测试先注释
                    SaveDLInfo();
                    #endregion



                    //string s1 = ConfigHelper.AppSettings("Version");
                    //string s2 = ConfigHelper.AppSettings("xmlPath");
                    //string s3 = ConfigHelper.ConnectionStrings("JudgeDoc").ConnectionString;
                    Close();
                    break;
                case loginRes.nameerror:
                    MsgBox.Warn("用户名不存在！");
                    return;
                case loginRes.passerror:
                    MsgBox.Warn("密码错误！");
                    return;
                case loginRes.ineffective:
                    MsgBox.Warn("用户未生效！");
                    return;
                case loginRes.expired:
                    MsgBox.Warn("用户已过期！");
                    return;
                case loginRes.sysNon:
                    MsgBox.Warn("用户不具备该系统的权限");
                    return;
            }
        }
        #endregion

        #region 打开用户注册窗体（功能已屏蔽）
        /// <summary>
        /// 打开用户注册窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            RegeditForm regeditFrom = new RegeditForm();
            regeditFrom.ShowDialog();
            if (Gvar.uo != null)
                cobUserName.Text = Gvar.uo.m_loginName;
        }
        #endregion

        #region 保存用户名到文件
        /// <summary>
        /// 保存用户名到文件
        /// </summary>
        /// <param name="userName"></param>
        private void SaveUserInfo(string userName)
        {
            try
            {
                if (configInfo.LoginInfo == null)
                    configInfo.LoginInfo = new LoginInformation() { UserNames = new List<string>() { } };

                if (!configInfo.LoginInfo.UserNames.Contains(userName))
                {
                    configInfo.LoginInfo.UserNames.Add(userName);
                    var info = JsonConvert.SerializeObject(configInfo);
                    File.WriteAllText(path, info);
                }
        
                if (!cobUserName.AutoCompleteCustomSource.Contains(userName))
                {
                    cobUserName.AutoCompleteCustomSource.Add(userName);
                }
                //    if (!File.Exists(path))
                //{
                //    FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write);
                //    StreamWriter sw = new StreamWriter(fs);
                //    sw.WriteLine(userName);
                //    sw.Close();
                //    fs.Close();
                //}
                //else
                //{
                //    if (!cobUserName.AutoCompleteCustomSource.Contains(userName))
                //    {
                //        cobUserName.AutoCompleteCustomSource.Add(userName);
                //        StreamWriter sr = new StreamWriter(path, true);
                //        sr.WriteLine(userName);
                //        sr.Close();
                //    }
                //}
            }
            catch (Exception ex)
            {
                throw new Exception("保存用户信息发生错误:" + ex.Message);
            }
        }
        #endregion

        #region 从文件获取用户名
        /// <summary>
        ///从文件获取用户名
        /// </summary>
        private void GetUserInfo()
        {
            try
            {
                if (File.Exists(path))
                {
                    var info = File.ReadAllText(path);
                    if (!string.IsNullOrWhiteSpace(info))
                    {
                        configInfo = JsonConvert.DeserializeObject<ConfigInfo>(info);
                        if (configInfo.LoginInfo != null && configInfo.LoginInfo.UserNames.Any())
                        {
                            configInfo.LoginInfo.UserNames.ForEach(x => {
                                if (!cobUserName.AutoCompleteCustomSource.Contains(x))
                                {
                                    cobUserName.AutoCompleteCustomSource.Add(x);
                                }
                                alUsers.Add(x);
                            });
                        }
                    }
                    //StreamReader str = new StreamReader(path, true);
                    //string res = str.ReadLine();
                    //while (res != null)
                    //{
                       
                    //    res = str.ReadLine();
                    //}
                    //str.Close();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("获取用户信息发生错误:" + ex.Message);
            }
        }

        /// <summary>
        /// 获取登录信息
        /// </summary>
        private void GetDLInfo()
        {
            try
            {
                if (File.Exists(DLpath))
                {
                    string res = File.ReadAllText(DLpath);
                    string[] dlInfos = res.Split(new char[] { '；' },StringSplitOptions.RemoveEmptyEntries) ;
                    if (dlInfos.Length > 0)
                    {
                        foreach (var item in dlInfos)
                        {
                            string name = item.Split('，')[0].ToString().Trim();
                            DlInfo dl = new DlInfo() { Version= item.Split('，')[1].ToString(), xmlPath= item.Split('，')[2].ToString(), JudgeDoc = item.Split('，')[3].ToString(), ElementsRuleConfigPath = item.Split('，')[4].ToString() };
                            if (!dicDLInfo.ContainsKey(name))
                            {
                                if (!cmbDL.AutoCompleteCustomSource.Contains(name))
                                {
                                    cmbDL.AutoCompleteCustomSource.Add(name);
                                }
                                alDLInfo.Add(name);
                                dicDLInfo.Add(name, dl);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("获取服务器展示信息发生错误:" + ex.Message);
            }
        }

        /// <summary>
        /// 保存配置文件
        /// </summary>
        public void SaveDLInfo()
        {
            if (dicDLInfo.ContainsKey(cmbDL.Text.Trim()))
            {
                DlInfo dlInfo = dicDLInfo[cmbDL.Text.Trim()];
                ConfigHelper.SetValue("Config\\system.config", "//appSettings", "Version",dlInfo.Version,"key");
                ConfigHelper.SetValue("Config\\system.config", "//appSettings", "xmlPath", dlInfo.xmlPath, "key");
                ConfigHelper.SetValue("Config\\system.config", "//appSettings", "ElementsRuleConfigPath", dlInfo.ElementsRuleConfigPath, "key");
                ConfigHelper.SetValue("Config\\db.config", "//connectionStrings", "JudgeDoc", dlInfo.JudgeDoc,"name");
                //刷新 ConfigurationManager 配置 
                FieldInfo fieldInfo = typeof(ConfigurationManager).GetField("s_initState", BindingFlags.NonPublic | BindingFlags.Static);
                if (fieldInfo != null) fieldInfo.SetValue(null, 0);
            }
        }
        #endregion

    }

   
}
